package com.example.tool.service.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.tool.bean.ddaiexcel.AddAiSheetRecordsRequest;
import com.example.tool.bean.form.StatisticStockSpecInForm;
import com.example.tool.conf.WarehouseConfEnum;
import com.example.tool.erp.sdk.api.goods.dto.GoodsSearchResponse;
import com.example.tool.erp.sdk.api.wms.dto.StockSearch2Response;
import com.example.tool.erp.sdk.api.wms.stockspec.dto.StockSpecChangeHistoryQueryResponse;
import com.example.tool.util.DDUtil;
import com.example.tool.util.DateUtil;
import com.example.tool.util.WDTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    private static final String YYYY_MM_DD = "yyyy-MM-dd";
    private static final List<String> frozenProductsWarehouseNos = Arrays.asList(WarehouseConfEnum.CQ_DP.getCode(), WarehouseConfEnum.HF_DP.getCode(),
            WarehouseConfEnum.TZ_DP.getCode(), WarehouseConfEnum.SH_DP.getCode(), WarehouseConfEnum.DX_DP.getCode(), WarehouseConfEnum.CS_DP.getCode(),
            WarehouseConfEnum.SY_DP.getCode(), WarehouseConfEnum.WH_DP.getCode());
    //冻品工作表
    private static final String frozenProductsWorkbookId = "ZX6GRezwJlyDpZnPI5PXgNoz8dqbropQ";
    //冻品机器人token
    private static final String frozenProductsToken = "101a5440fe4fff791a4c91b19baa4130bcad271cf240f5295cfdea4d3d13a191";
    //冻品机器人Secret
    private static final String frozenProductsSecret = "SEC694fb5801f22ec15ede03797ffcabc69665b18d8ef8542fc9e1c0adc7ebd0829";
    //冻品数据表头
    public static final List<String> frozenProductsHeaderValues = Arrays.asList("货品编号", "货品名称", "仓库名称", "仓库编号", "可发库存", "采购在途", "排查时间");
    //冻品消息标题
    private static final String frozenProductsMsgTitle = "冻品品库存不足:详情可见";

    //常温工作表
    private static final String roomTemperatureWorkbookId = "N7dx2rn0JbN94QjnU5ONRMRNJMGjLRb3";
    //常温机器人token
    private static final String roomTemperatureToken = "101a5440fe4fff791a4c91b19baa4130bcad271cf240f5295cfdea4d3d13a191";
    //常温机器人Secret
    private static final String roomTemperatureSecret = "SEC694fb5801f22ec15ede03797ffcabc69665b18d8ef8542fc9e1c0adc7ebd0829";
    //常温消息标题
    private static final String roomTemperatureMsgTitle = "常温品库存不足:详情可见";
    //常温数据表头
    private static final List<String> roomTemperatureHeaderValues = Arrays.asList("货品编号", "货品名称", "仓库名称", "仓库编号", "可发库存", "采购在途", "排查时间");
    private static final Integer updateBatchSize = 1000;

    private static final List<String> specStockTimeTemperatureHeaderValues = Arrays.asList(
            "商家编码",
            "湖南-长沙（冻品仓）",
            "湖北-武汉（冻品仓）",
            "重庆-重庆（冻品仓）",
            "安徽-合肥（冻品仓）",
            "上海-上海（冻品仓）",
            "山东-济南（冻品仓）",
            "广东-德信（冻品仓）",
            "辽宁-沈阳（冻品仓）",
            "湖南-长沙（常温仓）",
            "浙江-义乌（常温仓）",
            "江西-南昌（常温仓）",
            "广东-江高（常温仓）",
            "浙江-龙港（常温仓）"
            );


    @Override
    public void scheduledImportClaims() {
        List<StockSearch2Response.Detail> stockDetail = findStockDetail();
        processingData(stockDetail);
    }

    @Override
    public void statisticStockSpecIn(StatisticStockSpecInForm specInForm) {
        List<String> specNoList = specInForm.getSpecNoList();
        if (CollectionUtil.isEmpty(specNoList)) {
            log.error("商品编号为空");
            return;
        }
        // 初始化参数
        Set<String> specStockTimeSet = new HashSet<>(specStockTimeTemperatureHeaderValues);
        AddAiSheetRecordsRequest.Record[] recordArr = new AddAiSheetRecordsRequest.Record[specNoList.size()];
        int index = 0;
        for (String specNo : specNoList) {
            Date endTime = new Date();
            Map<String, Object> specStockTimeMap = new HashMap<>();
            specStockTimeMap.put("商家编码", specNo);
            // 按月遍历查询（先查6个月）
            for (int i = 0;i < 5;i++) {
                Date startTime = DateUtil.addDays(endTime, -30);
                try {
                    List<StockSpecChangeHistoryQueryResponse.Data> dataList = WDTUtil.queryStockSpecChangeHistory(specNo, DateUtil.dateToStr(startTime), DateUtil.dateToStr(endTime));
                    for (StockSpecChangeHistoryQueryResponse.Data data : dataList) {
                        // 剔除退货入库
                        if (data.getSrcOrderType() == null
                                || data.getSrcOrderType() == 12
                                || data.getSrcOrderType() == 13
                                || data.getSrcOrderType() == 14) {
                            continue;
                        }
                        // 获取对应仓库名称
                        String warehouseName = data.getWarehouseName();
                        if (!specStockTimeSet.contains(warehouseName)) {
                            continue;
                        }
                        if (specStockTimeMap.containsKey(warehouseName)) {
                            continue;
                        }
                        String createdTime = data.getCreated();
                        specStockTimeMap.put(warehouseName, DateUtil.convertTimeStampToDateTimeV2(createdTime));
                    }
                } catch (Exception e) {
                    log.error("商品编号:{}查询失败:", specNo, e);
                }
                // 若仓库统计完成则提前退出
                if (specStockTimeMap.size() >= specStockTimeSet.size()) {
                    break;
                }
                endTime = startTime;
            }
            // 落入AI表格
            AddAiSheetRecordsRequest.Record record = new AddAiSheetRecordsRequest.Record();
            record.setFields(specStockTimeMap);
            recordArr[index++] = record;
        }
        if (recordArr[0] != null) {
            DDUtil.addAiSheetRecords(null, "商品库存入库时间测试", recordArr);
        }
    }


    private List<StockSearch2Response.Detail> findStockDetail() {
        DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.now();
        String endSearchTime = endTime.format(FORMATTER);
        String startSearchTime = endTime.minusHours(24).format(FORMATTER);
        List<StockSearch2Response.Detail> allStockDetail = new ArrayList<>();
        StockSearch2Response stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, 1, 0);
        Integer total = stockSearch2Response.getTotal();
        int pageSize = 1000;
        if (total > 0) {
            int totalPages = (int) Math.ceil((double) total / pageSize);
            for (int pageNo = 0; pageNo < totalPages; pageNo++) {
                stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, pageSize, pageNo);
                allStockDetail.addAll(stockSearch2Response.getDetailList());
            }
        }
        allStockDetail = allStockDetail.stream().distinct().collect(Collectors.toList());
        return allStockDetail;
    }

    private void processingData(List<StockSearch2Response.Detail> stockDetail) {
        List<String> specNos = stockDetail.stream().map(StockSearch2Response.Detail::getSpecNo).distinct().collect(Collectors.toList());
        List<String> goodNos = new ArrayList<>();
        for (String specNo : specNos) {
            GoodsSearchResponse goodsSearchResponse = WDTUtil.goodsSearchSpecNo(specNo);
            for (GoodsSearchResponse.GoodsSearchGoodsDto goodsDto : goodsSearchResponse.getGoodsInfos()) {
                for (GoodsSearchResponse.GoodsSearchSpecDto specDtoss : goodsDto.getSpecDtos()) {
                    if (ObjectUtil.equal(specDtoss.getProp6(), "出售ing")) {
                        goodNos.add(goodsDto.getGoodsNo());
                    }
                }
            }
        }

        goodNos = goodNos.stream().distinct().collect(Collectors.toList());
        List<String> finalGoodNos = goodNos;
        stockDetail = stockDetail.stream().filter(sd -> {
            if (!finalGoodNos.contains(sd.getGoodsNo())) {
                return false;
            }
            if (sd.getAvailableSendStock().compareTo(BigDecimal.ZERO) <= 0 && sd.getPurchaseNum().compareTo(new BigDecimal("200")) > 0) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        SimpleDateFormat YYYY_MM_DD_SDF = new SimpleDateFormat(YYYY_MM_DD);
        Date date = new Date();
        String yyyyMMdd = YYYY_MM_DD_SDF.format(date);
        List<StockSearch2Response.Detail> frozenProducts = stockDetail.stream().filter(sd -> frozenProductsWarehouseNos.contains(sd.getWarehouseNo())).collect(Collectors.toList());
        if (!frozenProducts.isEmpty()) {
            List<List<String>> values = frozenProducts.stream().map(fp -> Arrays.asList(fp.getGoodsNo(), fp.getGoodsName(), fp.getWarehouseName(), fp.getWarehouseNo(), fp.getAvailableSendStock().toString(), fp.getPurchaseNum().toString(), yyyyMMdd)).collect(Collectors.toList());
            DDUtil.updateAiExcelSendMsg(frozenProductsWorkbookId, frozenProductsSecret, frozenProductsToken, null, null, values, yyyyMMdd, frozenProductsHeaderValues, frozenProductsMsgTitle, "", "", updateBatchSize);
        }


        List<StockSearch2Response.Detail> roomTemperature = stockDetail.stream().filter(sd -> !frozenProductsWarehouseNos.contains(sd.getWarehouseNo())).collect(Collectors.toList());
        if (!roomTemperature.isEmpty()) {
            try {
                // 休眠1000毫秒（1秒）
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                log.error("休眠异常:", e);
            }
            List<List<String>> values = roomTemperature.stream().map(fp -> Arrays.asList(fp.getGoodsNo(), fp.getGoodsName(), fp.getWarehouseName(), fp.getWarehouseNo(), fp.getAvailableSendStock().toString(), fp.getPurchaseNum().toString(), yyyyMMdd)).collect(Collectors.toList());
            DDUtil.updateAiExcelSendMsg(roomTemperatureWorkbookId, roomTemperatureSecret, roomTemperatureToken, null, null, values, yyyyMMdd, roomTemperatureHeaderValues, roomTemperatureMsgTitle, "", "", updateBatchSize);
        }
    }
}
